<template>
  <div
    class="home"
    @click="touch"
    @touchmove="move"
    :style="{
      backgroundColor: $store.getters.getye
        ? '#1e1e1e'
        : bgcolorArr[$store.getters.XselecedIndex],
      fontSize: '16px',
    }"
  >
    <div
      class="page-read-top"
      v-bind:style="{
        backgroundColor: $store.getters.getye
          ? '#1e1e1e'
          : bgcolorArr[$store.getters.XselecedIndex],
        color: $store.getters.getye ? '#e4e6eb' : '#1e1e1e',
      }"
    >
      {{ novel.novels[selectPartIndex - 1]?.articleTitle }}
    </div>
    <!--       顶部 : 第一章 我是穿越者     动态变化 -->

    <van-popup
      v-model="show2"
      position="left"
      class="flextopbottom"
      duration="0.2"
      :lazy-render="false"
      :style="{
        height: '100%',
        width: '60%',
        backgroundColor: '#ffffff',
        color: 'black',
      }"
    >
      <div class="content flex">
        <van-image
          style="border-radius: 0.5rem; padding: 0.3rem 0; overflow: hidden"
          width="100"
          height="100"
          :src="novel.picUrl"
        />

        <div>
          <span>{{ novel.name }}</span>
          <br />
          <span>{{ novel.author }}</span>
        </div>
      </div>
      <div ref="scrollele" class="scroll">
        <van-list finished-text="none">
          <van-cell
            class="cellbg oneline"
            v-for="(item, index) in novel.novels"
            :key="index"
            @click="tojump(partObj.id, index + 1)"
            :class="{ selectcolor: index == selectPartIndex }"
            replace
          >
            <div class="novelTitle">
              <div class="left">
                {{ item.articleTitle }}
              </div>
              <div class="right" v-show="item.status">
                <van-icon name="lock" />
              </div>
            </div>
          </van-cell>
        </van-list>
      </div>

      <!-- <div ref="scrollele" class="scroll"> -->

      <!-- <div class="rightTop" :style="{ height: '68vh' }">
 
        <van-cell class="cellbg" v-for="( item, index ) in novel.novels" :key="index" :title="item.articleTitle"
          @click="tojump(partObj.id , index)"
          :class="{ selectcolor: index == selectPartIndex }" icon="location-o"   replace />

        </div> -->
      <!-- </div> -->
      <!-- 弹性布局中的 定位 绝对定位 会  定位会生效 -->
      <!-- 弹性布局中的 定位 绝对定位 会 脱离标准量吗?  -->
    </van-popup>

    <top @show="show = false" :show="show"></top>

    <!-- 文章内容 -->
    <!-- <van-pull-refresh v-model="refreshing" @refresh="onRefresh"> -->

    <van-list
      ref="list"
      v-model="loading"
      @load="onLoad"
      offse="500"
      :finished="finished"
    >
      <van-cell
        ref="contentlist"
        :border="false"
        v-addobserver="observerObj"
        :tag="item.sort"
        style="background-color: none"
        class="cellbgc"
        v-for="item in articleArr"
        :key="item.title"
      >
        <template>
          <div>
            <div style="">
              <section class="contenttext">
                <!-- <h1>{{item.articleTitle}}</h1> -->
                <div
                  :class="{ addcolor: $store.getters.getye }"
                  v-bind:style="{
                    fontSize: $store.getters.contentfonsize + 'rem',
                  }"
                  v-html="item.articleContent"
                ></div>
              </section>
            </div>
            <div
              v-show="item.status && !item.userStatus"
              :class="{
                mask: item.status && !item.userStatus,
                mask2: item.status && !item.userStatus && $store.getters.getye,
              }"
            >
              <div class="fenge">
                <van-divider @click.stop="topay" class="fenge2" style="">
                  Pay ${{ novel.Price }} to unlock the entire novel
                </van-divider>
                <div
                  class="fenggepostion"
                  style="text-align: center; padding: 0 2rem"
                >
                  <p>THANK YOU!</p>
                  Show your support to inspire the writer to come up with more
                  fantastic stories
                </div>
              </div>
            </div>
          </div>
        </template>
      </van-cell>
    </van-list>

    <!--  支付 -->
    <!-- <van-popup  class="pay"  @click.stop  :overlay="false"   v-model:show="payshow"></van-popup> -->
    <van-popup
      class="pay"
      @click.stop
      v-model:show="payshow"
      round
      @close="close"
      position="bottom"
      safe-area-inset-bottom
      style="transition: all 0.3s"
    >
      <Pay :novel="novel"></Pay>
    </van-popup>

    <div></div>

    <!-- 单击 显示底部 -->
    <bottom
      :safe-area-inset-bottom="true"
      @leftchangde="getmenu"
      :show="show"
      :bgcolorArr="bgcolorArr"
      :change="change"
      :selecedIndex="selecedIndex"
    >
      <template #fsnum>
        <!-- 字体大小 -->
        <van-slider
          step="1.5"
          min="5.5"
          max="10"
          v-model="getfonsize"
          bar-height="4px"
          active-color="#ee0a24"
        />
      </template>
      <template #partNum>
        <!--  章节 -->

        <p class="partNum">
          <!-- {{novel.novels[selectPartIndex]?.articleTitle}}  |  {{  percentage}} -->
          {{ novel.novels[modelselecedIndex]?.articleTitle }} | {{ percentage }}
        </p>
        <div class="press">
          <div class="inner"><i class="iconfont icon-yuyinjiantou"></i></div>

          <van-slider
            @change="sliderchangde"
            step="1"
            min="1"
            :max="novel.novels.length"
            v-model="modelselecedIndex"
            bar-height="4px"
            active-color="#ee0a24"
          />

          <div class="inner"><i class="iconfont icon-yuyinjiantou"></i></div>
        </div>
      </template>
    </bottom>

    <!-- 登录 -->

    <van-popup
      class="topmove"
      v-model:show="login"
      :overlay="false"
      :style="{
        padding: '0.5rem 0.3rem',
        width: '90%',
        borderRadius: '20px',
        height: '80%',
      }"
    >
      <login @isshow="login = false" :reader="true"></login>
    </van-popup>
  </div>
</template>

<script>
import { getMenu, getpart } from '@api/reader.js';
import bottom from '@com/reader/bottom.vue';
import top from '@com/reader/top.vue';
import login from './login.vue';
import Pay from '@com/pay/pay';

//  用个变量来储存
var _this = {};

export default {
  name: 'reader',
  data() {
    return {
      itemfinished: false,
      itemloading: false,

      boforeJump: false,

      loading: false, // 加载状态 true 为加载显示
      //  上下
      show: false,

      // 左侧弹窗
      show2: false,

      //  登录是否显示
      login: false,

      // 支付是否显示
      payshow: false,

      judge: false,

      modelfontSize: 3,

      // 当前页面
      partObj: {
        id: 0,
        sort: 0,
      },
      finished: false,

      // 颜色选择组合
      bgcolorArr: ['#f5f5f5', '#f7f0e8', '#e6e6e6', '#cad9e8'],

      modelselecedIndex: 0,

      selecedIndex: '0',
      // 当前选中颜色 2
      change: 2,

      // 左侧菜单栏
      patrItem: [],
      novel: {
        novels: [],
      },
      // 当前阅读文章顺序
      selectPartIndex: 3,
      //  创建的时候去跟  路由进行绑定

      top: 100,
      articleArr: [],
      observerObj: new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting) {
          //  从底部出来 才换
          // console.log( "进来了 准备替换",entries[0].boundingClientRect);
          if (entries[0].boundingClientRect.bottom > 800) {
            //  限制他是从 顶部进来
            console.log('进来了', entries[0].target.getAttribute('tag'));
            // if(this.articleArr.length!=1){
            this.selectPartIndex = entries[0].target.getAttribute('tag') - 0;
            // }
          }
        } else if (entries[0].boundingClientRect.top > 0) {
          console.log('离开了');

          if (this.boforeJump) {
            this.selectPartIndex =
              entries[0].target.getAttribute('tag') + '' - 0;
          } else {
            this.selectPartIndex =
              entries[0].target.getAttribute('tag') - 1 + '' - 0;
            this.boforeJump = false;
          }
        }
      }),

      // 左侧顶部头像高度
      menuTopHeight: 100,
      scrollnum: 20,
      refreshing: false, // 上拉刷新
      lastNum: 2,
    };
  },

  watch: {
    // 监听 发送请求的 的变化, 表示目前是阅读的是第几章
    selectPartIndex(value) {
      console.log('观察者下标', value);
      // console.log( "添加历史记录",this.$route.params.id , value);
      this.$store.commit('CHANGE_LOCATION_HISTORY', {
        id: this.$route.params.id,
        sort: value,
      });
    },

    async $route(to) {
      // this.boforeRouter =this.$route.params.sort
      // console.log("路由发生变化", this.$route.params );
      // if(true){
      //   this.boforeJump= true
      // this.partObj = this.$route.params
      // if(this.articleArr.length ==1){
      //      this.articleArr=[]
      //   await this._getpart(this.partObj)
      // }else{
      //   this.articleArr=[]
      //    this.judge = true
      //    await this._getpart(this.partObj)
      // }
      // }
      // to还是阅读器 就发送请求 ,不是就不发送

      if (to.name == 'reader') {
        this.partObj = this.$route.params;
        this.selectPartIndex = this.partObj.sort;
        await this._getpart(this.partObj, true);

        console.log(this.selectPartIndex);

        this.finished = false;
      }
    },
  },
  async created() {
    console.log('创建');
    this.modelselecedIndex = this.$route.params.sort - 0;

    this.partObj = this.$route.params;
    // this.selectPartIndex = this.$route.params.sort

    let { data } = await getMenu({ id: this.$route.params.id });
    // this.patrItem = data.novel
    this.novel = data;
    console.log(this.novel);
  },
  methods: {
    close() {
      console.log('关闭了');
      this.$children[3].$children[0].userstatus = 0;
      // console.log(  this.$children[3].$children);
    },
    //上拉
    // async onRefresh(){

    //     if(this.partObj.sort- this.lastNum <0){

    //       this.refreshing = false
    //       return
    //     }
    //     let sort  = this.partObj.sort- this.lastNum
    //     this.lastNum =this.lastNum+1
    //   await  this._getpart({  id:this.partObj.id , sort })
    //   this.refreshing = false
    // },
    // 获得文章
    async _getpart(options, status) {
      let reslut = await getpart(options);
      if (!reslut.articleContent) {
        this.finished = true;
      }

      reslut.articleContent = reslut.articleContent.replace(/(.*\r)/g, (n) => {
        if (n.trim()) {
          return '<p>' + n + '</p>';
        } else {
          return '';
        }
      });

      status
        ? (this.articleArr = [reslut])
        : this.refreshing
        ? this.articleArr.unshift(reslut)
        : this.articleArr.push(reslut);
      console.log('listcell', this.articleArr);

      this.loading = false;
      if (reslut.status && !reslut.userStatus) {
        this.finished = true;
      }
      this.partObj.sort++;
    },

    sliderchangde(value) {
      console.log('进度条', value);

      if (this.$route.query.id) {
        this.$router.replace({
          path:
            '/reader/' +
            this.partObj.id +
            '/' +
            value +
            '?id=' +
            this.$route.query.id,
        });
      } else {
        this.$router.replace({
          path: '/reader/' + this.partObj.id + '/' + value,
        });
      }
    },

    touch() {
      this.show = !this.show;
    },

    // 触底刷新
    async onLoad() {
      // 加载之前 需要改变一下章节
      if (this.judge) {
        this.judge = false;
        this.loading = false;
        console.log('拦截触发');
        return;
      }

      console.log('onload', this.partObj);
      await this._getpart(this.partObj);
    },

    getchangeSize(num) {
      this.fontSize = num;
    },

    // 移动屏幕 隐藏功能区
    move() {
      this.show = false;
    },
    topay() {
      // // 用户是否登录getmenu
      if (localStorage.getItem('token')) {
        // 有登陆正常付费
        this.payshow = true;
      } else {
        //   弹一个登录

        this.login = true;
      }
    },

    getmenu() {
      this.show2 = true;
      this.$nextTick(() => {
        // console.log(this.$refs.scrollele.offsetHeight);
        // var ele = this.$refs.scrollele.children[this.selectPartIndex]
        // var result = ele.getBoundingClientRect()
        // this.$refs.scrollele.scrollTop = ele.offsetHeight * this.selectPartIndex - (this.$refs.scrollele.offsetHeight / 2) + 100
      });
    },
    tojump(id, sort) {
      this.show2 = !this.show2;
      if (this.$route.query.id) {
        this.$router.replace(
          '/reader/' + id + '/' + sort + '?id=' + this.$route.query.id
        );
      } else {
        this.$router.replace('/reader/' + id + '/' + sort);
      }
    },
  },
  components: {
    bottom,
    top,
    login,
    Pay,
  },
  directives: {
    addobserver: {
      inserted(el, bind) {
        bind.value.observe(el);
      },
    },
  },
  computed: {
    getfonsize: {
      set(value) {
        return this.$store.commit('CHANGE_FONSIZE', value);
      },
      get() {
        // console.log( 'this.$store' , this.$store);
        return this.$store.getters.getfonsize;
      },
    },
    percentage() {
      return (
        parseInt((this.selectPartIndex / this.novel.novels.length) * 100) + '%'
      );
    },
  },
  deactivated() {
    console.log('组件被取消了');
    this.articleArr = [];
  },
};
</script>

<style lang="scss">
.pay {
  width: 100vw;
  // height: 85vh;
  // overflow-y: auto;
  // padding: 0 10px;
}

.fenggepostion {
  position: absolute;
  bottom: -3rem;
}

.fenge {
  width: 100vw;
  position: absolute;
  bottom: 41%;
  z-index: 9;
  padding: 3rem 0;
  color: #efb64c;

  border-color: #efb64c;
}

.fenge2 {
  color: #efb64c;

  border-color: #efb64c;
}

.home {
  min-height: 100vh;
}

.cellbgc {
  background: none;
  padding: 0;
}

.one {
  /*1.先强制一行内显示文本*/
  white-space: nowrap;
  /*2.超出的部分隐藏*/
  overflow: hidden;
  /*3.文字用省略号替代超出的部分*/
  text-overflow: ellipsis;
  min-height: 100vh;
}

.flextopbottom {
  display: flex;
  flex-direction: column;

  .slip {
    // width: 3rem;
    // height: 3rem;
    background-color: #fff;
    position: absolute;
    top: 100px;
    right: 0.3rem;
    z-index: 333;
  }
}

.addcolor {
  color: #e4e6eb;
}

.scroll {
  overflow: auto;

  .cellbg {
    // background-color: #fff;
    color: #2222;
  }

  .selectcolor {
    color: #ed424b;
  }
}

.rightTop {
  position: absolute;
  top: 200px;
  right: 20px;
  z-index: 999;
  height: 7rem;

  .van-slider--vertical {
    width: 0px;
  }

  .van-slider__button {
    width: 0.6rem;
    height: 1rem;
    border-radius: 4rem;
    background-color: #ed424b;
  }
}

.changhtml {
  height: 4rem;
  overflow: hidden;
}

.partNum {
  color: #1e1e1e;
  margin: 0.3rem;
}

.press {
  display: flex;
  align-items: center;

  .icon-yuyinjiantou {
    font-size: 1.5rem;
    color: #e4e6eb;
  }

  .fontA {
    font-size: 0.7rem;
    color: #1e1e1e;
    margin: 0 0.6rem;
  }

  .inner:nth-child(1) {
    transform: rotate(90deg);
  }

  .inner:nth-child(3) {
    transform: rotate(-90deg);
  }
}

.page-read-top {
  padding: 0.4rem;
  margin-bottom: 0.4rem;
  //  font-size: 0.6rem;
  position: fixed;
  top: 0;
  left: 0;
  width: 12rem;
  z-index: 999;
  // background-color: #f7f0e8;
}

.topmove {
  top: 50%;
}

.contenttext {
  word-break: break-all;
  text-indent: 1em;

  position: relative;
  padding: 0 0.3rem;
  padding-top: 1.6rem;
  min-height: 95vh;

  div p:nth-child(1) {
    display: block;
    width: 90%;
    font-size: 1rem;
    text-align: center;
    font-weight: 800;
    line-height: 1.3rem;
    margin: 0.7rem;
  }

  p {
    margin: 0.3rem;
    line-height: 1.7em;
  }
}

.mask::after {
  display: block;
  content: '';
  position: absolute;
  top: 0px;
  left: 0px;
  width: 150%;
  height: 100%;
  box-shadow: inset -2rem -16rem 3rem#ffff;
}

.mask2::after {
  box-shadow: inset -2rem -16rem 3rem #0c0c0c;
}

.novelTitle {
  // 修改目录
  color: black;
  display: flex;
  justify-content: space-between;

  .left {
    white-space: nowrap; //规定文本不换行
    text-overflow: ellipsis; //显示省略符号来代表被修剪的文本
    overflow: hidden;
    width: 170px;
  }
}
</style>
